import json
import random
from time import sleep

import requests

from app.libs.ctms.data import create_waybill_data, get_waybill_id_data, create_shift_data,create_shift_data_driver, pay_id_data, pay_data
from app.libs.ctms.method import http_ctms, result_se, update_parameter, pay
from app.libs.ctms.ip import get_current_time
from app.libs.log import logger
'''
上游录单
中游支付
'''

def waybill_no():
    return http_ctms(path='/waybill/generateWaybillNo', data='', method='get')


def shift_no():
    return http_ctms(path='/shift/generateShiftNo', data='', method='get')


# def waybillNoList(amount):
#     """
#     :param amount: 创建运单数量
#     :return: 创建运单id列表
#     """
def created_waybill(is_receipt,data=create_waybill_data):
    logger.warning(waybill_no())
    update = {
        'waybillNo': waybill_no(),
        'projectName': '顺丰-滁州-瑞旋',
        'projectNo': "440SF000128016",
        "customer": "顺丰速运有限公司",
        "customerNo": "440SF000128",
        "customerOrderNo": '客户订单号' + str(random.randint(0, 10000000)),
        "hasReceipt": is_receipt
    }
    update_parameter(update, data)
    waybill = http_ctms(path='/waybill/createWaybill', data=data)
    # logger.debug(waybill.json())
    try:
        assert_ = waybill.json()['content']['waybillNo'] == data['waybillNo']
    except:
        print(waybill.json())
        return waybill.json()
    return result_se(waybill, assert_, 'return')

# list1 = []
# for i in range(2):
#     waybill=created_waybill()
#     list1.append(waybill['content']['waybillNo'])
#     sleep(1)
# print('运单号列表：{}'.format(list1))
    # return list1


# waybill_list = list1


def waybill_id(waybill_list,data=get_waybill_id_data,not_list=False):
    update = {
        "waybillNoList": waybill_list
    }
    #shiftWaybillDTOList
    update_parameter(update, data)
    waybillId = http_ctms(path='/waybill/pageWaybillList', data=data)
    # logger.debug(waybillId.json())
    waybillId = waybillId.json()['content']['data']
    if not_list:
        return waybillId.json()['content']['data'][0]['id']
    else:
        id_list = []
        for i in waybillId:
            id = i['id']
            id_list.append(id)
        return id_list


# waybill_id_list = waybill_id(waybill_list)
# print('运单id列表:{}'.format(waybill_id_list))


def created_shift(pay_method,waybill_id_list,data=create_shift_data,up_amount=100, below_amount=80, finalAmount=20):
    # waybill_id_list=waybill_id(waybill_list)
    shiftWaybillDTOList=[{"waybillId": i} for i in waybill_id_list]

    update = {
        "shiftNo": shift_no(),
        "shiftWaybillDTOList": shiftWaybillDTOList
    }
    data = pay(data, paymentMethod=pay_method,up_amount=up_amount, below_amount=below_amount, finalAmount=finalAmount)  # 支付方式，司机信息修改封装
    update_parameter(update, data)  # 部分信息封装

    logger.debug('调度单创建入参{}'.format(data))
    waybillId = http_ctms(path='/shift/saveAndUpdateShift', data=data)
    result = result_se(data=waybillId, return_or_print='return')

    return result


# shift_id = created_shift(waybill_list)['content']['id']
# print(shift_id)

def shift_particulars(shift_id):
    #查看调度单详情获取运单信息
    list1=[]
    shiftParticulars=http_ctms(path='/shift/getLoadWaybillList',data={"shiftId":shift_id})
    result=shiftParticulars.json()['content']['waybillList']['data']
    for i in result:
        list1.append(i['waybillNo'])
    return list1
# print(shift_particulars(shift_id))
def dispatch(shift_id):
    '''调度单派单
        :param shift_id: 调度单id
        '''
    dispatch_shift_data = {"shiftIdList": [{"id": shift_id}]}
    dispatch_shift = http_ctms(path='/shift/dispatchShift', data=dispatch_shift_data)
    return dispatch_shift.json()

# print(dispatch(shift_id))

def send(shift_id):
    '''调度单发车
      :param shift_id: 调度单id
      '''
    send_shift_data = {"shiftIdList": [{"id": shift_id, "sendTime": get_current_time(-1)}]}
    send_shift = http_ctms(path='/shift/sendShift', data=send_shift_data)
    return send_shift.json()
#
#
# print(send(shift_id))
#
#
def arrive(shift_id):
    '''调度单到达
    :param shift_id: 调度单id
    '''
    arrive_shift_data = {"shiftIdList": [{"id": shift_id, "arriveTime": get_current_time(-1)}]}
    arrive_shift = http_ctms(path='/shift/arriveShift', data=arrive_shift_data)
    return arrive_shift.json()
#
#
# print(arrive(shift_id))
#
#
def receipt_upload(waybill_id_list, waybill_list):
    '''运单上传
    :param waybill_id_list: 运单id列表
    :param waybill_list: 运单号列表
    '''
    if len(waybill_id_list) == len(waybill_list):
        for i in range(len(waybill_id_list)):
            receipt_data = {
                "waybillId": waybill_id_list[i],
                "waybillNo": waybill_list[i],
                "receipt": "[\"ctms/uat/2021-07-28/receiptConfirm/M627-014__uuid__347bc318-8625-446f-ac9c-9e80932b0eb1__uuid__"
                           "c7c79370-e118-47d2-b8fe-f1bc255fe9c5.jpg\",\"ctms/uat/2021-07-28/receiptConfirm/M628-003__uuid__4"
                           "6faa4d9-978a-4898-be56-095d8133f4d5__uuid__4171ce90-08cf-4901-aa68-c08162c23da5.jpg\"]",
                "remark": ""
            }
            receipt = http_ctms(path='/waybill/receipting', data=receipt_data)
            # print(receipt.json())
#
#
# receipt_upload(waybill_id_list, waybill_list)
#
#
def receipt_confirm(waybill_id_list):
    '''运单签收
    :param waybill_id_list: 运单id列表
    '''
    receipt_confirm = http_ctms(path='/waybill/receiptConfirm', data=waybill_id_list)
    logger.debug(receipt_confirm.json())
    return receipt_confirm.json()
def create_common_bill(ip='https://ctms.uat-ingress.keking.cn'):
    token = 'eyJlbmNyeXB0ZWREYXRhIjoiWERqSmFpeDNyQmIrU0k2Sys2K2FpUmo3WmdNbGhXNFlUVmVXd3ZyRHNUSzI4Z2xjeTJMaFBVYkJlVUNQdmNQVWpKR0pvU0NVZWIyalpMblQwelNyQXhoRTFVZlNpeXBvNW1qVmNkMGhrS0VSdS9iaitkalV1QVFoNUZzampBL0hVUU9aRC8xc0h0UDJuYzBRWWhGR0JodDJVNDNJSGNDYWV0VnBNZEV6emNWTHN1VUYzSVJXZUZ5ajV2a1dOZkVxNXVmTXFKQSs5Rk51NmtLcW8xeE8zcE9oclc3RFVZL2Irdlo1RmlIUmlTbXZmYUREYStIcFl6eEQ4SzBIQStKMFVDWTNRR0M3OW53UGNSdUp0bTVPZDM4eUpobEUxU3FzVkVJNmNDZktpR04yU01UcElFL0lqSURiYkk1M3lqUDI4d0tKWnVFTU9aUjRDcnUxcGM1RThQL3EweHg3YzVKdk9KUm83REZjVWxURHY1RVp0SDJUdHZRVnFvMWpCSXU1Z1djL2g1STUwS2tCL3cwRzlkZUdqVTlxVGV3eXIwWGRITzJLVmJaTG5iSjJiOThsak1qR3FORE4rZ2x1MkowRmpaOGRkaWJKcEJ2T3VXUFFhbEtHTyt2SGs0YkFTQUhreFk3QWc0N3dGSGRvTlVHMklFNG12YzUxTnREeTRqcWpVYStSY21uQ3JsT0FDY2ZNVlhSKzdxT3EyaHpkVEtUSDhYcjdTZVJmZTRSMnBYSHMwNnpHWkRmL0tJeXpzMWtld3RzVjFsemk4VEtYb29kQTVTZ0p0bDU4dGlOM2pGRVAxWE5BQ29NUEF0VDRncytNMHBPV3BESGl2TnRSeTFzUSsrbUpNSGszajgxWDVpK3BSSkE2YVU5enZ3NDBpNitmL2FmY2VOZnZsaWUwUEJ4b0JQb0NDQmhjWUY1dW01Njl5UTQwS0EzTU1QaWJEeVVhcG5telFnPT0iLCJ3cmFwcGVkS2V5IjoiUVN0SlVVT3F5Q0llWU42cmZ4a2x2RUdkczhvbUorc3g0VnlFWjlYL3dlRXhKVE5kUFA5RmEyY3VaY0YyYzJmTUFxS3ByN3lpODZ1NW0zUndERjQ3MjhPcUpkeTJ0eEpzUGYyWlRVeVpWSm8za0VDRG9iSXFIcWE3OTlTbWE1VlNETnlzNzVLT0kyMzZXZnFhNHppV1J3S0FGV080V3I4dzFIR1ZxTFYzOFlnPSJ9=='
    headers = {'content-type': 'application/json;charset=UTF-8',
               'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
               'token': token}
    data = {
        "contractNo": "HT-20120216465100013-1",
        "sheetDateEnum": "SEND_DATE",
        "year": "2021",
        "month": "09",
        "projectName": "顺丰-亚申",
        "projectNo": "20120216465100013",
        "downCompanyName": "",
        "startDate": "2021-09-01 00:00:00",
        "endDate": "2021-09-30 23:59:59",
        "upCompanyName": "顺丰控股股份有限公司",
        "generateBillOperator": "003301001"
    }
    re = requests.post(url=ip + '/bill/createCommonBill',headers=headers,data=json.dumps(data))
    print(re.text)
    if re.json()['content']['waybillFareAmount']==0:
        delete=requests.post(url=ip + '/bill/deleteBillCommon',headers=headers,data=json.dumps({'id':re.json()['content']['id']}))
        if delete.json()['msg']=='成功':
            print('账单总金额为0，删除该账单成功')
        else:
            print(delete.json())
    else:
        print('账单创建成功')
        que = requests.post(url=ip + '/bill/confirmBillCommon', headers=headers,
                           data=json.dumps({'billCommonNo': re.json()['content']['billCommonNo']}))
        if que.json()['msg'] == '成功':
            print('账单确认成功')
            return re.json()['content']['billCommonNo']
        else:
            print('账单确认错误，原因：{}'.format(que.json()))

# print(receipt_confirm(waybill_id_list))
#
#
# #支付相关
#
# def pay_id(data=pay_id_data):
#     sleep(2)  # 遇到奇怪的问题可以加等待时间试试
#     update = {
#         "waybillNoList": waybill_list
#     }
#     update_parameter(update, data)
#     print(data)
#     id = http_ctms(path='/payOrder/getBillPayOrderList', data=data,system='ys')
#     return id.json()['content']['data']
# #
# #
# print(pay_id())
# pay_data1=pay_id()
# # print(pay_data1)
# #
# #线下付
# def offline_pay(data=pay_data):
#     update = {
#         "payWay": "OFFLINE",
#         "detail": pay_data1
#     }
#     update_parameter(update, data)
#     print(data)
#     pay_result = http_ctms(path='/payOrder/pay', data=data,system='ys')
#     return pay_result.json()
# print(offline_pay())
# #
# #线上付
# def online_pay(data=pay_data):
#     update = {
#         "payWay": "ONLINE",
#         "receiveWay": "TO_CARD",
#         "detail": pay_data1
#     }
#     update_parameter(update, data)
#     print(data)
#     pay_result = http_ctms(path='/payOrder/pay', data=data, system='ys') #ctms发起支付申请
#     return pay_result.json()
#
# print(online_pay())